/**
 * Handle all WebSocket connection and communication. Easily manage the functions that are
 * triggered by WebSocket events. Setup the WebSocket params and then connect.
 *
 * @param   String  Full WebSocket url which includes ws:// or wss://
 * @param   Object  An object which holds the event functions to be called which are:
 *                  close, failed, open, receive
 *
 * @return  Null
 **/
function wsap_client(url, wsParams) {

    /**
     * Constructor
     **/
    var ws, receive_func;
    if (connect(url)) {

        // Bind Connection Open
        if (typeof wsParams.onOpen == "function")
            ws.onopen = wsParams.onOpen;

        // Bind Message Received
        if (typeof wsParams.onReceive == "function") {

            receive_func = wsParams.onReceive;
            ws.onmessage = receive;

        }

        // Bind Connection Close
        if (typeof wsParams.onClose == "function")
            ws.onclose = wsParams.onClose;

    } else {

        // Run Connection Failed Function
        if (typeof wsParams.onFailed == "function")
            wsParams.onFailed(ws);

    }

    /**
     * Connect to WebSocket server and return true or false on connect
     *
     * @param   String      Full WebSocket server url.
     *
     * @return  Boolean     True if Web Socket connection is established and communication is
     *                      possible. False otherwise.
     **/
    function connect(url)
    {

        ws = new WebSocket(url);
        return (ws.readyState < 2);

    }

     /**
     * Get WebSockets response, parse json and return response object to the receive if it 
     * exists.
     *
     * @param  Object      Message event object
     *
     * @return Null
     **/
    function receive(e)
    {

        if (typeof receive_func == "function") {

             eval("var response = " + e.data);
             receive_func(response);

         }

     }

    /**
     * Close WebSocket connection if it is open
     **/
    this.close = function() 
    {

        if (ws.readyState < 2)
            ws.close();

    }

    /**
     * This is a temp function I am using for debuging
     **/
     this.getWs = function()
     {

         return ws;

     }

    /**
     * Send string to WebSocket Server
     *
     * @param   String  Message to be sent to the WebSocket server
     *
     * @return  Boolean
     **/
    this.send = function(msg)
    {

        return ws.send(msg);

    }

}
